{% extends 'base.html' %}

{% block title %}提示词管理 - AI Prompt Hub{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <!-- 左侧分类栏 -->
        <div class="col-md-2">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">分类</h5>
                    <button class="btn btn-sm btn-primary" onclick="showCategoryModal()">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <div class="list-group list-group-flush" id="categoryList">
                    <a href="#" class="list-group-item category-item active-category" data-id="all">
                        全部
                    </a>
                    {% for category in categories %}
                    <a href="#" class="list-group-item category-item" data-id="{{ category.id }}">
                        {{ category.name }}
                    </a>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 中间提示词列表 -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">提示词列表</h5>
                    <button class="btn btn-primary" onclick="showPromptModal()">
                        <i class="fas fa-plus"></i> 新建提示词
                    </button>
                </div>
                <div class="list-group list-group-flush prompt-list" id="promptList">
                    {% for prompt in prompts %}
                    <a href="#" class="list-group-item prompt-item" data-id="{{ prompt.id }}">
                        <div class="d-flex w-100 justify-content-between align-items-start">
                            <div class="prompt-main">
                                <h6 class="mb-1">{{ prompt.title }}</h6>
                                <div class="prompt-meta">
                                    <span class="category-badge">{{ prompt.category.name }}</span>
                                    <span class="time-text">{{ prompt.updated_at|date:"Y-m-d H:i" }}</span>
                                </div>
                            </div>
                            <div class="status-badge">
                                {% if prompt.updated_at|date:"Y-m-d" == prompt.created_at|date:"Y-m-d" %}
                                    <span class="badge bg-success">新建</span>
                                {% else %}
                                    <span class="badge bg-info">更新</span>
                                {% endif %}
                            </div>
                        </div>
                    </a>
                    {% empty %}
                    <div class="list-group-item text-center text-muted">
                        暂无提示词
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 右侧详情 -->
        <div class="col-md-6">
            <div class="card prompt-detail d-none" id="promptDetail">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0" id="detailTitle"></h5>
                    <div>
                        <button class="btn btn-primary btn-sm" onclick="editPrompt()">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="deletePrompt()">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <p class="text-muted" id="detailCategory"></p>
                    <h6>描述：</h6>
                    <p id="detailDescription"></p>
                    <h6>内容：</h6>
                    <div class="content-area">
                        <pre id="detailContent" style="white-space: pre-wrap;"></pre>
                        <button class="btn btn-sm btn-secondary copy-btn" onclick="copyContent()">
                            <i class="fas fa-copy"></i> 复制
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 提示词模态框 -->
<div class="modal fade" id="promptModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="promptModalTitle">新建提示词</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="promptForm">
                    <input type="hidden" id="promptId">
                    <div class="mb-3">
                        <label class="form-label">标题</label>
                        <input type="text" class="form-control" id="promptTitle" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="promptCategory" required>
                            {% for category in categories %}
                            <option value="{{ category.id }}">{{ category.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="promptDescription" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">内容</label>
                        <textarea class="form-control" id="promptContent" rows="5" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="savePrompt()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 分类模态框 -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">新建分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="categoryForm">
                    <div class="mb-3">
                        <label class="form-label">分类名称</label>
                        <input type="text" class="form-control" id="categoryName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="categoryDescription" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">消</button>
                <button type="button" class="btn btn-primary" onclick="saveCategory()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentPromptId = null;

    // 显示提示词详情
    function showPromptDetail(id) {
        $.get(`/prompts/detail/${id}/`, function(data) {
            currentPromptId = id;
            $('#detailTitle').text(data.title);
            $('#detailCategory').text(`分类：${data.category}`);
            $('#detailDescription').text(data.description);
            $('#detailContent').text(data.content);
            $('#promptDetail').removeClass('d-none');
        });
    }

    // 复制内容
    function copyContent() {
        const content = $('#detailContent').text();
        navigator.clipboard.writeText(content).then(function() {
            Swal.fire({
                icon: 'success',
                title: '复制成功',
                showConfirmButton: false,
                timer: 1500
            });
        });
    }

    // 显示提示词模态框
    function showPromptModal(id = null) {
        $('#promptId').val(id);
        $('#promptModalTitle').text(id ? '编辑提示词' : '新建提示词');
        if (id) {
            // 显示加载状态
            Swal.fire({
                title: '加载中...',
                didOpen: () => {
                    Swal.showLoading();
                },
                allowOutsideClick: false
            });

            // 加载现有数据
            $.get(`/prompts/detail/${id}/`, function(data) {
                $('#promptTitle').val(data.title);
                $('#promptCategory').val(data.category_id);
                $('#promptDescription').val(data.description);
                $('#promptContent').val(data.content);
                
                Swal.close();  // 关闭加载提示
                $('#promptModal').modal('show');
            }).fail(function(xhr, status, error) {
                Swal.fire('错误', '加载数据失败，请重试', 'error');
            });
        } else {
            $('#promptForm')[0].reset();
            $('#promptModal').modal('show');
        }
    }

    // 保存提示词
    function savePrompt() {
        const id = $('#promptId').val();
        const data = {
            title: $('#promptTitle').val().trim(),
            category: $('#promptCategory').val(),
            description: $('#promptDescription').val().trim(),
            content: $('#promptContent').val().trim(),
            csrfmiddlewaretoken: '{{ csrf_token }}'
        };

        // 表单验证
        if (!data.title) {
            Swal.fire('错误', '标题不能为空', 'error');
            return;
        }
        if (!data.content) {
            Swal.fire('错误', '内容不能为空', 'error');
            return;
        }
        if (!data.category) {
            Swal.fire('错误', '请选择分类', 'error');
            return;
        }

        // 显示加载状态
        Swal.fire({
            title: '保存中...',
            didOpen: () => {
                Swal.showLoading();
            },
            allowOutsideClick: false
        });

        $.ajax({
            url: id ? `/prompts/update/${id}/` : '/prompts/create/',
            type: 'POST',
            data: data,
            success: function(response) {
                if (response.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: id ? '更新成功' : '创建成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('错误', response.message || '保存失败', 'error');
                }
            },
            error: function(xhr, status, error) {
                Swal.fire('错误', '服务器错误，请稍后重试', 'error');
            }
        });
    }

    // 删除提示词
    function deletePrompt() {
        if (!currentPromptId) return;

        Swal.fire({
            title: '确认删除？',
            text: "删除后将无法恢复！",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: '确认删除',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(`/prompts/delete/${currentPromptId}/`, {
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }, function(response) {
                    if (response.status === 'success') {
                        location.reload();
                    } else {
                        Swal.fire('错误', response.message, 'error');
                    }
                });
            }
        });
    }

    // 显示分类模态框
    function showCategoryModal() {
        $('#categoryForm')[0].reset();
        $('#categoryModal').modal('show');
    }

    // 保存分类
    function saveCategory() {
        const data = {
            name: $('#categoryName').val(),
            description: $('#categoryDescription').val(),
            csrfmiddlewaretoken: '{{ csrf_token }}'
        };

        // 表单验证
        if (!data.name) {
            Swal.fire('错误', '分类名称不能为空', 'error');
            return;
        }

        // 显示加载状态
        Swal.fire({
            title: '保存中...',
            didOpen: () => {
                Swal.showLoading();
            },
            allowOutsideClick: false,
            allowEscapeKey: false,
            allowEnterKey: false
        });

        $.ajax({
            url: '/prompts/category/create/',
            type: 'POST',
            data: data,
            success: function(response) {
                console.log('Response:', response);  // 调试输出
                if (response.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: '创建成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('错误', response.message || '创建失败', 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);  // 调试输出
                Swal.fire('错误', '服务器错误，请稍后重试', 'error');
            }
        });
    }

    // 点击分类时的处理函数
    function filterPromptsByCategory(categoryId) {
        // 显示加载状态
        Swal.fire({
            title: '加载中...',
            didOpen: () => {
                Swal.showLoading();
            },
            allowOutsideClick: false
        });

        // 发送请求获取过滤后的提示词列表
        $.get('/prompts/filter/', { category: categoryId }, function(response) {
            if (response.status === 'success') {
                // 更新提示词列表
                updatePromptList(response.prompts);
                Swal.close();
            } else {
                Swal.fire('错误', response.message || '加载失败', 'error');
            }
        }).fail(function() {
            Swal.fire('错误', '服务器错误，请稍后重试', 'error');
        });
    }

    // 更新提示词列表的函数
    function updatePromptList(prompts) {
        const promptList = $('#promptList');
        promptList.empty();

        if (prompts.length === 0) {
            promptList.append(`
                <div class="list-group-item text-center text-muted">
                    暂无提示词
                </div>
            `);
            return;
        }

        prompts.forEach(prompt => {
            const isNew = new Date(prompt.updated_at).toDateString() === new Date(prompt.created_at).toDateString();
            const statusBadge = isNew ? 
                '<span class="badge bg-success">新建</span>' : 
                '<span class="badge bg-info">更新</span>';

            promptList.append(`
                <a href="#" class="list-group-item prompt-item" data-id="${prompt.id}">
                    <div class="d-flex w-100 justify-content-between align-items-start">
                        <div class="prompt-main">
                            <h6 class="mb-1">${prompt.title}</h6>
                            <div class="prompt-meta">
                                <span class="category-badge">${prompt.category_name}</span>
                                <span class="time-text">${prompt.updated_at}</span>
                            </div>
                        </div>
                        <div class="status-badge">
                            ${statusBadge}
                        </div>
                    </div>
                </a>
            `);
        });

        // 重新绑定点击事件
        $('.prompt-item').click(function() {
            $('.prompt-item').removeClass('active');
            $(this).addClass('active');
            showPromptDetail($(this).data('id'));
        });
    }

    // 修改事件绑定部分
    $(document).ready(function() {
        // 点击提示词列表项
        $('.prompt-item').click(function() {
            $('.prompt-item').removeClass('active');
            $(this).addClass('active');
            showPromptDetail($(this).data('id'));
        });

        // 点击分类
        $('.category-item').click(function(e) {
            e.preventDefault();
            $('.category-item').removeClass('active-category');
            $(this).addClass('active-category');
            const categoryId = $(this).data('id');
            filterPromptsByCategory(categoryId);
        });
    });

    // 编辑提示词
    function editPrompt() {
        if (!currentPromptId) return;
        showPromptModal(currentPromptId);  // 使用当前选中的提示词ID打开模态框
    }
</script>
{% endblock %}

{% block extra_css %}
<style>
    .prompt-list {
        max-height: calc(100vh - 200px);
        overflow-y: auto;
    }

    .prompt-item {
        padding: 12px 16px;
        border-left: 3px solid transparent;
        transition: all 0.2s ease;
    }

    .prompt-item:hover {
        background-color: rgba(114, 137, 218, 0.1);
        border-left-color: #7289da;
    }

    .prompt-item.active {
        background-color: rgba(114, 137, 218, 0.15);
        border-left-color: #7289da;
    }

    .prompt-main {
        flex: 1;
        min-width: 0;  /* 防止文本溢出 */
    }

    .prompt-item h6 {
        margin: 0;
        font-size: 0.95rem;
        font-weight: 500;
        color: var(--text-primary) !important;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .prompt-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 4px;
    }

    .category-badge {
        font-size: 0.75rem;
        color: #fff;
        background-color: rgba(114, 137, 218, 0.3);
        padding: 2px 8px;
        border-radius: 12px;
    }

    .time-text {
        font-size: 0.7rem;
        color: var(--text-secondary);
    }

    .status-badge .badge {
        font-size: 0.7rem;
        font-weight: normal;
        padding: 3px 8px;
    }

    .badge.bg-success {
        background-color: #43b581 !important;
        opacity: 0.9;
    }

    .badge.bg-info {
        background-color: #7289da !important;
        opacity: 0.9;
    }

    /* 自定义滚动条 */
    .prompt-list::-webkit-scrollbar {
        width: 6px;
    }

    .prompt-list::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .prompt-list::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
    }

    .prompt-list::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }

    .prompt-item {
        color: var(--text-primary);
        text-decoration: none;
    }

    .prompt-item:hover {
        color: var(--text-primary);
        text-decoration: none;
        background-color: rgba(114, 137, 218, 0.1);
        border-left-color: #7289da;
    }

    /* 确保列表项在深色主题下有正确的背景色 */
    .list-group-item {
        background-color: var(--dark-secondary);
        border-color: rgba(255,255,255,0.1);
    }
</style>
{% endblock %}
